<template>
  <!-- 出租下单弹窗 -->
  <el-dialog title="出租卡位" :visible.sync="dialogVisible" @close="close" :close-on-click-modal="false" width="1000px">
    <!-- <div>
      <el-button type="primary" plain @click="close">返回</el-button>
    </div> -->
    <div class="task_goods_add_box" v-loading="loading">
      <div class="flex chengzuren">
        <b>租赁方：</b>
        <el-select @change="selectChange" v-if="tenantList&&tenantList.length" v-model="form.zulinfangId" placeholder="请选择店铺" clearable filterable>
          <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName" :value="dict.tenantId" />
        </el-select>
      </div>
      <div class="flex chengzuren">
        <b>管理方式：</b>
        <el-radio-group v-model="form.zulinType" @change="zulinTypeChange">
          <el-radio :label="1">按游戏运营商</el-radio>
          <el-radio :label="2">整体管理</el-radio>
        </el-radio-group>
      </div>
      <div class="flex chengzuren">
        <b>选号方式：</b>
        <el-radio-group v-model="form.xuanhaoType" @change="xuanhaoTypeChange">
          <el-radio :label="1">系统随机</el-radio>
          <el-radio :label="2">手动选号</el-radio>
        </el-radio-group>
      </div>
      <div v-if="phoneNumberList&&phoneNumberList.length">
        <div style="margin:15px 0;">
          <b>详情：</b>
        </div>
        <div class="rowitem flex head">
          <span>运营商</span>
          <span>可分配数</span>
          <span v-if="form.xuanhaoType==1">分配数</span>
          <span v-if="form.xuanhaoType==2">分配号码</span>
          <span>到期时间</span>
        </div>
        <div class="rowitem flex" v-for="(item,i) in phoneNumberList" :key="i">
          <span>{{item.carrierName}}</span>
          <span>{{item.kechuzu}}</span>
          <span v-if="form.xuanhaoType==1">
            <el-input-number :disabled="item.kechuzu==0" style="width:100px" :controls="false" :precision="0" :step="1" step-strictly v-model="item.num" placeholder="请输入"></el-input-number>
          </span>
          <span v-if="form.xuanhaoType==2">
            <el-button :disabled="item.kechuzu==0" plain type="primary" @click="openPhoneSelect(item)">选择号码</el-button>
            <span class="yixuan">已选 {{item.telInfo? item.telInfo.length:0 }}</span>
          </span>
          <span>
            <el-date-picker style="width:150px" v-model="item.expireTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期">
            </el-date-picker>
          </span>
        </div>
      </div>
    </div>
    <div class="tip">提示：本系统不参与出租费用收取，请自行谈好合作后再将号码授权给租赁方！</div>
    <div slot="footer" class="center">
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" @click="submitForm('form')" v-loading="loading">提交</el-button>
    </div>

    <div class="haoma">
      <el-dialog title="选择号码" :visible.sync="telNumberShow" @close="close2" append-to-body :close-on-click-modal="false" width="780px">
        <div>
          <!-- <div>
            请选择要分配的号码：
          </div> -->
          <div class="flex">
            <el-input style="width: 200px;margin-right: 15px;" v-model="queryParams.tel" placeholder="请输入手机号" clearable size="small" />
            <el-button type="primary" @click="search">搜索</el-button>
          </div>
          <div class="custom-checkbox" style="margin: 5px 0;">
            <label style="width: 120px;" >
              <input
                @change="isAllCheckChange"
                type="checkbox"
                :value="true"
                v-model="isAllCheck"
              />
              全选
            </label>
          </div>
          <div class="flex custom-checkbox" style="flex-wrap: wrap;">
            <label style="width: 120px;" v-for="item in telNumberList" :key="item.id">
              <input
                type="checkbox"
                :value="item.id"
                v-model="checkTelNumberList"
              />
              {{ item.tel }}
            </label>
          </div>
        </div>
        <div slot="footer" class="center">
          <el-button @click="close2()">取消</el-button>
          <el-button type="primary" @click="saveTelNumber" v-loading="loading">提交</el-button>
        </div>
      </el-dialog>
    </div>
  </el-dialog>
</template>
<script>
import phoneApi from "@/api/phoneManage";
export default {
  name: "",
  data() {
    return {
      isAllCheck: false,
      telNumberListInit: [], //初始 可选的号码列表
      telNumberList: [], //可选的号码列表
      checkTelNumberList: [], //选择的号码列表
      queryParams: {
        tel: "",
      },
      telNumberShow: false,
      dialogVisible: false,
      loading: false,
      totalPhoneNumber: 0,
      form: {
        zulinType: 1,
        zulinfangId: "",
        xuanhaoType: 1,
      },
      selectTenantInfo: "",
      phoneNumberList: [],
      selects: [],
      queryParams: {
        pageSize: 10,
        pageNum: 1,
      },
      rules: {
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        type: [{ required: true, message: "请输入", trigger: "change" }],
        intervalDays: [
          { required: true, message: "请输入", trigger: "change" },
        ],
      },

      currentRow: null,
    };
  },
  created() {},
  computed: {
    tenantList() {
      return this.$store.getters.tenantList;
    },
  },
  methods: {
    // 打开弹窗
    open() {
      this.dialogVisible = true;
      this.getList();
    },
    // 打开选择号码的弹窗
    openPhoneSelect(item) {
      console.log("%c Line:146 🥒 item", "color:#4fff4B", item);
      this.currentRow = item;
      this.checkTelNumberList = [];
      this.isAllCheck = false;
      this.telNumberShow = true;
      // 回显已经选择的号码
      if(item.telInfo&&item.telInfo.length){
        item.telInfo.forEach(r=>{
          this.checkTelNumberList.push(r.id)
        })
      }
      // 初始化可选的号码

      this.initTelList();
    },
    // 从运营商信息里面格式化可以选择的号码
    initTelList() {
      this.telNumberList = [];
      this.telNumberListInit = [];
      if (this.form.zulinType == 2) {
        this.telNumberList = [...this.currentRow.unLeaseInfo]
      } else {
        if (this.currentRow.unused_tels) {
          const list = this.currentRow.unused_tels.split(",");
          if (list && list.length) {
            list.forEach((r) => {
              this.telNumberList.push({
                id: r.split("-")[0],
                tel: r.split("-")[1],
              });
            });
          }
        }
      }

      this.telNumberListInit = JSON.parse(JSON.stringify(this.telNumberList));
    },
    // 查找号码
    search() {
      if (this.queryParams.tel) {
        this.telNumberList = this.telNumberListInit.filter((r) =>
          r.tel.includes(this.queryParams.tel)
        );
      } else {
        this.telNumberList = JSON.parse(JSON.stringify(this.telNumberListInit));
      }
    },
    // 全选号码
    isAllCheckChange(e) {
      if (this.isAllCheck) {
        // this.checkTelNumberList = JSON.parse(
        //   JSON.stringify(this.telNumberList)
        // );
        this.checkTelNumberList = [];
        this.telNumberList.forEach((r) => {
          this.checkTelNumberList.push(r.id);
        });
      } else {
        this.checkTelNumberList = [];
      }
    },
    // 选择号码完成
    saveTelNumber() {
      this.checkTelNumberList;

      if (this.checkTelNumberList.length == 0) {
        return this.$message.error("请选择号码！");
      }
      const temp = []
      this.checkTelNumberList.forEach(id=>{
        this.telNumberListInit.forEach(r=>{
          if(r.id==id){
            temp.push(r)
          }
        })
      })
      this.currentRow.num = this.checkTelNumberList.length
      this.currentRow.telInfo = JSON.parse(
        JSON.stringify(temp)
      );
      this.close2();
    },
    // 获取未加入出租池的手机号
    getList() {
      this.loading = true;
      phoneApi
        .getLeaseInfo({
          zulinType: this.form.zulinType,
        })
        .then((response) => {
          // console.log("%c Line:122 🌶 response", "color:#fca650", response);
          this.totalPhoneNumber = response.data.total;
          this.loading = false;
          if (this.form.zulinType == 2) {
            this.phoneNumberList = [
              {
                carrierId: "",
                carrierName: "全部",
                kechuzu: response.data.unLeaseInfo
                  ? response.data.unLeaseInfo.length
                  : 0,
                num: 0,
                expireTime: "",
                unLeaseInfo: response.data.unLeaseInfo,
              },
            ];
          } else if (this.form.zulinType == 1) {
            const infoList = response.data.unLeaseInfo;
            const list = [];
            if (infoList && infoList.length) {
              infoList.forEach((r) => {
                list.push({
                  ...r,
                  kechuzu: r.unused_tels ? r.unused_tels.split(",").length : 0,
                  num: 0,
                  expireTime: "",
                });
              });
            }
            this.phoneNumberList = JSON.parse(JSON.stringify(list));
          }
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 出租类型改变
    zulinTypeChange(e) {
      this.getList();
    },
    // 选号类型改变
    xuanhaoTypeChange(){
      this.phoneNumberList.forEach(r=>{
        r.num = 0
        r.telInfo = null
      })
    },
    // 选择店铺改变
    selectChange(e) {
      this.tenantList.forEach((r) => {
        if (r.tenantId == e) {
          this.selectTenantInfo = { ...r };
        }
      });
    },

    // 重置
    reset() {
      this.form = {
        pageNum: 1,
        pageSize: 10,
      };
      this.$refs.form.resetFields();
    },

    submitForm(formName) {
      if (!this.form.zulinfangId) {
        return this.$alert("请选择租赁方！");
      }
      const arr = [];
      let flag = true;
      let numFlag = true;
      this.phoneNumberList.forEach((r) => {
        if (r.num && r.num > 0) {
          if (!r.expireTime) {
            flag = false;
          }
          if (r.num > r.kechuzu) {
            numFlag = false;
          }
          const tempObj = {
            carrierId: r.carrierId,
            num: r.num,
            expireTime: r.expireTime,
          }
          if(this.form.xuanhaoType==2){
            // 手动选号的
            tempObj.telInfo = [...r.telInfo]
          }
          arr.push({
            ...tempObj
          });
        }
      });
      if (arr.length == 0) {
        return this.$alert("最少填写一个运营商的出租数量！");
      }
      if (!flag) {
        return this.$alert("出租的号请输入到期时间！");
      }
      if (!numFlag) {
        return this.$alert("出租的数量不能大于可租数量！");
      }

      this.$confirm(
        `提交后立即生效！确定将以上卡位授权给${this.selectTenantInfo.tenantName}使用吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.loading = true;
          const obj = {
            ...this.form,
          };
          if (this.form.zulinType == 2) {
            obj.num = arr[0].num;
            obj.expireTime = arr[0].expireTime;
            obj.telInfo = arr[0].telInfo;
          } else {
            obj.telLeaseDetailsVos = arr;
          }
          // return console.log("%c Line:342 🥟 obj", "color:#7f2b82", obj);
          
          phoneApi
            .telLeaseDetailsSave(obj)
            .then((res) => {
              this.loading = false;
              this.$message.success(res.msg);
              this.dialogVisible = false;
              this.$parent.getList();
            })
            .catch((err) => {
              this.loading = false;
            });
        })
        .catch(() => {});
    },
    close() {
      this.form = {
        zulinType: 1,
        zulinfangId: "",
        xuanhaoType: 1,
      };

      this.dialogVisible = false;
    },

    close2() {
      this.telNumberShow = false;
    },
  },
};
</script>
<style scoped lang="scss">
.task_goods_add_box {
  width: 100%;
  .chengzuren {
    align-items: center;
    margin-bottom: 15px;
  }
  .rowitem {
    line-height: 34px;
    &.head {
      > span {
        background-color: #f7f7f7;
      }
    }
    > span {
      width: 150px;
      padding: 5px 10px;
      border: 1px solid #f1f1f1;
      border-top: none;
      border-right: none;
      &:nth-of-type(3) {
        width: 200px;
      }
      &:last-child {
        width: 200px;
        border-right: 1px solid #f1f1f1;
      }
      .yixuan {
        margin-left: 10px;
      }
    }
  }
}
::v-deep .el-dialog__body {
  max-height: calc(100vh - 240px) !important;
}
.tip {
  color: red;
  margin-top: 10px;
}
::v-deep .el-radio input[aria-hidden="true"] {
  display: none !important;
}
::v-deep .no-transition .el-checkbox__input,
::v-deep .no-transition .el-checkbox__label {
  transition: none !important;
}
// ::v-deep .input[type="checkbox"]{
//   border-color: #6c5dd3;
// }
// ::v-deep input[type="checkbox"]:checked + ::v-deep label:before {
//     background: #2196F3 !important;
//     border-color: #2196F3 !important;
//   }
.custom-checkbox label{
  display: flex;
  align-items: center;
  margin-bottom: 3px;
  cursor: pointer;
}
</style>
<style>



/* 设置未选中样式 */
.custom-checkbox input[type="checkbox"] {
  position: relative;
  width: 13px;
  height: 13px;
  line-height: 13px;
  border: 1px solid #949494;
  border-radius: 2px;
  margin-right: 4px;
  
 
/* 取消默认样式 */
  -webkit-appearance: none;
}
/* 设置选中样式 */
.custom-checkbox input[type="checkbox"]:checked {
  background-color: #6c5dd3;
}
.custom-checkbox input[type="checkbox"]:checked::after {
  content: "✓";
  position: absolute;
  top: 0;
  width: 13px;
  height: 13px;
  color: #fff;
  text-align: center;
  }
</style>
